<template>
	<div class="newPage">
		<div class="header_wrap" :style="`padding-top: ${statusBarHeight}px`">
			<div class="goback" @click="goBack">
				<image class="goback_img" src="@/static/index2/index17.png" mode="widthFix"></image>
			</div>
			{{ info }}
			<div class="add_people" @click="handleMenu" :class="{'small': lang == 'ru'}">
				<span class="add_text"
					:class="{'small': lang == 'ru'}">{{ lang == 'ru' ? "групповой чат" : "发起群聊" }}</span>
				<image class="add_img" src="@/static/chat/communicate.png" mode="widthFix"></image>
			</div>
		</div>
		<div :class="['TUI-contact-search-main']">
			<u-search v-if="lang != 'ru'" class="TUI-contact-search-main-input" :placeholder="searchingPlaceholder"
				v-model="searchValue" shape="square" :clearabled="true" :show-action="false" height="80"
				search-icon-color="#AAABAD" color="#1D1D1D" placeholder-color="#AAABAD" @search="search"
				@blur="search"></u-search>
			<u-search v-if="lang == 'ru'" class="TUI-contact-search-main-input"
				:placeholder="'Введите идентификатор пользователя/группового чата для поиска'" v-model="searchValue"
				shape="square" :clearabled="true" :show-action="false" height="80" search-icon-color="#AAABAD"
				color="#1D1D1D" placeholder-color="#AAABAD" @search="search" @blur="search"></u-search>
		</div>
		<div class="search_tip">
			{{ isSearching && lang != "ru" ? "用户ID示例: “好友手机号”" : 'Пример идентификатора пользователя: "номер телефона пользователя"' }}
		</div>
		<scroll-view scroll-y="true" class="scroll-Y">
			<template v-if="isSearch">
				<div class="list_item" v-for="(item, key) in contactSearchResult.user.list" :key="key">
					<Avatar class="list_img" useSkeletonAnimation :url="item.avatar" size="88rpx" />
					<div class="list_name">{{ item.nick || item.userID }}</div>
					<div :class="{'is_long': lang == 'ru'}">
						<div class="list_btn list_btn1" @click.stop="handleIngroup(item)">
							<image class="btn_img" src="@/static/chat/add_people.png" mode="widthFix"></image>
							<span v-if="isCreate">{{ lang == 'ru' ? "Начать групповой чат" : "发起群聊" }}</span>
							<span v-else>{{ lang == 'ru' ? "Пригласить в группу" : "邀请进群" }}</span>
						</div>
						<div class="list_btn list_btn2" @click.stop="handleconnect(item)">
							<image class="btn_img" src="@/static/chat/communicate_white.png" mode="widthFix"></image>
							<span>{{ lang == 'ru' ? "Приветствовать" : "打招呼" }}</span>
						</div>
					</div>

				</div>
				<div class="TUI-contact-search-list-default" v-if="isContactSearchNoResult">
					{{ TUITranslateService.t("TUIContact.无搜索结果") }}
				</div>

			</template>

			<vipPopup v-if="vipShow" :show="vipShow" />
		</scroll-view>
	</div>
</template>
<script lang="ts">
	import {
		createC2CConversation,
	} from "@/common/public";
	import { addFriend, isFriend } from "../utils";
	export default {
		data() {
			return {
				lang: uni.getStorageSync('lang'),
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				info: "添加好友",
				isLoading: false,
				vipShow: false,
			}
		},
		onLoad() {

		},
		onShow() {
			TUITranslateService.changeLanguage(this.lang);
			if (this.lang == 'zh') {
				this.info = "添加好友";
			} else {
				this.info = "Добавить друзей";
			}
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			async handleconnect(item : any) {
				if (this.isLoading) return;
				try {
					let isBothFriend = await isFriend({
						userID: item.userID
					});
					if (!isBothFriend) {
						let obj = {
							to: item.userID,
							source: "AddSource_Type_Web",
						}
						addFriend(obj);
					}
					createC2CConversation(this.searchValue, this);
					this.isLoading = false;
				} catch (e) {
					//TODO handle the exception
					this.isLoading = false;
				}
			},
		}
	}
</script>

<script lang="ts" setup>
	import { ref, watch, computed, onMounted, onUnmounted } from "../../../adapter-vue";
	import { TUIStore, StoreName, TUITranslateService, IGroupModel } from "@tencentcloud/chat-uikit-engine";
	import TUICore, { ExtensionInfo, TUIConstants } from "@tencentcloud/tui-core";
	import { IContactSearchResult } from "../../../interface";
	import { TUIGlobal } from "../../../utils/universal-api/index";
	import Avatar from "../../common/Avatar/index.vue";

	import Server from "../server";

	const isSearching = ref<boolean>(true);
	const searchValue = ref<string>("");
	const lang = getApp().globalData.lang;
	const searchingPlaceholder = TUITranslateService.t('TUIContact.输入ID');
	const contactSearchingStatus = ref<boolean>(false);

	const extensionList = ref<Array<ExtensionInfo>>([]);

	const TUIContactServer = Server.getInstance();

	if (lang != 'ru') {
		var t1 = '联系人'
		var t2 = '群聊'
	} else {
		var t1 = 'ФИО'
		var t2 = 'групповой чат'
	}
	const contactSearchResult = ref<IContactSearchResult>();

	const isContactSearchNoResult = computed(() : boolean => {
		return (
			!contactSearchResult.value?.user?.list[0] &&
			!contactSearchResult.value?.group?.list[0]
		);
	});

	const searchResult = ref<IContactSearchResult>({
		user: {
			label: t1,
			list: [],
		},
		group: {
			label: t2,
			list: [],
		},
	});
	let systemInfo = uni.getSystemInfoSync();
	let statusBarHeight = systemInfo.statusBarHeight;

	let isSearch = ref<boolean>(false)

	// 搜索
	const search = async () => {
		if (!searchValue.value) {
			return;
		}
		isSearch.value = true;

		TUICore.callService({
			serviceName: TUIConstants.TUISearch.SERVICE.NAME,
			method: TUIConstants.TUISearch.SERVICE.METHOD.SEARCH_USER,
			params: {
				userID: 'gluz_' + searchValue.value,
			},
		}).then((res : any) => {
			searchResult.value.user.list = res.data;
		}).catch((error : any) => {
			searchResult.value.user.list = [];
		});
	};

	watch(
		() => searchResult.value,
		() => {
			TUIStore.update(
				StoreName.CUSTOM,
				"currentContactSearchResult",
				searchResult.value
			);
		},
		{
			deep: true,
			immediate: true,
		}
	);
	watch(
		() => isSearching.value,
		() => {
			TUIStore.update(
				StoreName.CUSTOM,
				"currentContactSearchingStatus",
				isSearching.value
			);
			if (isSearching.value) {
				searchValue.value = "";
				searchResult.value.user.list = [];
				searchResult.value.group.list = [];
			}
		},
		{
			deep: true,
			immediate: true,
		}
	);

	let isCreate = ref<boolean>(false)

	const contactListMap = ref<Array<any>>([]);

	function onGroupListUpdated(groupList : Array<IGroupModel>) {
		contactListMap.value = groupList;
		if (!groupList.length) {
			isCreate.value = true;
		} else {
			isCreate.value = false;
		}
	}

	onMounted(() => {
		extensionList.value = [
			...TUICore.getExtensionList(TUIConstants.TUISearch.EXTENSION.SEARCH_MORE.EXT_ID),
		];

		TUIStore.watch(StoreName.CUSTOM, {
			currentContactSearchingStatus: onCurrentContactSearchingStatusUpdated,
			currentContactSearchResult: onCurrentContactSearchResultUpdated,
		});

		TUIStore.watch(StoreName.GRP, {
			groupList: onGroupListUpdated,
		});
	});

	onUnmounted(() => {

		TUIStore.unwatch(StoreName.CUSTOM, {
			currentContactSearchingStatus: onCurrentContactSearchingStatusUpdated,
			currentContactSearchResult: onCurrentContactSearchResultUpdated,
		});

		TUIStore.unwatch(StoreName.GRP, {
			groupList: onGroupListUpdated,
		});
	});

	// 全局公共方法
	TUIGlobal.updateContactSearch = search;
	TUIGlobal.closeSearching = () => {
		isSearching.value = false;
	};

	function onCurrentContactSearchResultUpdated(searchResult : IContactSearchResult) {
		contactSearchResult.value = searchResult;
	}
	function onCurrentContactSearchingStatusUpdated(searchingStatus : boolean) {
		contactSearchingStatus.value = searchingStatus;
	}

	let isCall = ref<boolean>(false);
	const handleMenu = () => {
		if (isCall.value) return;
		extensionList.value.map((item : any) => {
			if (item.text !== '发起单聊') {
				const { listener = { onClicked: () => { } } } = item;
				listener.onClicked(item);
				isCall.value = false;
			}


		})
	}

	const handleIngroup = async (item : any) => {
		if (isCreate.value) {
			handleSelectedResult([item]);
		} else {
			let isBothFriend = await isFriend({
				userID: item.userID
			});
			if (!isBothFriend) {
				let obj = {
					to: item.userID,
					source: "AddSource_Type_Web",
				}
				addFriend(obj);
			}
			TUIGlobal?.navigateTo({
				url: `/TUIKit/components/TUIContact/contact-search/addgroup?userID=${item.userID}`
			})
		}


	}

	const handleSelectedResult = (memberList : Array<any>) => {
		TUIStore.update(StoreName.CUSTOM, "isShowSelectFriendComponent", false);
		const callback = TUIContactServer.getOnCallCallback(TUIConstants.TUIContact.SERVICE.METHOD.SELECT_FRIEND);
		callback && callback(memberList);
	};
</script>

<style lang="scss" scoped>
	.newPage {
		width: 100%;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		height: 100%;
		/* #ifdef APP-PLUS */
		height: 100vh;
		/* #endif */
	}

	.header_wrap {
		flex: none;
		height: 88rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		line-height: 60rpx;
		color: #1D1D1D;
		font-weight: 500;
		letter-spacing: 3rpx;
		margin-bottom: 30rpx;
		position: relative;
		background-color: #fff;

		.add_people {
			position: absolute;
			z-index: 2;
			display: inline-flex;
			width: auto;
			height: 80rpx;
			bottom: 4rpx;
			right: 10rpx;
			align-items: center;
			justify-content: center;
			padding-right: 20rpx;

			&.small {
				bottom: 26%;
				flex-direction: column-reverse;
				transform: translateY(50%);
				height: auto;
			}

			.add_text {
				font-size: 28rpx;
				margin-right: 10rpx;

				&.small {
					font-size: 18rpx;
					line-height: 1.3;
				}
			}

			.add_img {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.goback {
			position: absolute;
			z-index: 2;
			display: inline-flex;
			width: 80rpx;
			height: 80rpx;
			bottom: 4rpx;
			left: 0;
			align-items: center;
			justify-content: center;

			.goback_img {
				width: 60rpx;
				height: 60rpx;
			}
		}
	}

	.TUI-contact-search {

		&-main {
			width: 100%;
			height: 60rpx;
			display: flex;
			flex: none;
			flex-direction: row;
			align-items: center;
			padding: 0 30rpx;
			justify-content: center;
			box-sizing: border-box;

			&-input {
				flex: 1;
				font-size: 28rpx;
				border-radius: 20rpx;
				border: none;
				line-height: 48rpx;

				::v-deep .u-input {
					flex: 1;
				}
			}

			&-input:focus {
				outline: none;
				border: 1px solid #006eff;
			}

			&-cancel {
				padding-left: 10px;
				user-select: none;
				cursor: pointer;
			}
		}
	}

	.search_tip {
		font-size: 24rpx;
		margin-top: 25rpx;
		color: #fd3c3c;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.scroll-Y {
		width: 100%;
		flex: 1;
		overflow: hidden;
		padding: 0 30rpx;
		box-sizing: border-box;

		.list_item {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-wrap: wrap;
			margin-bottom: 20rpx;

			.list_img {
				flex: none;
				margin-right: 20rpx;
			}

			.list_name {
				font-size: 32rpx;
				color: #1D1D1D;
				flex: 1;
				box-sizing: border-box;
				overflow: hidden;
				text-overflow: ellipsis;
				word-break: break-all;
				white-space: nowrap;
			}

			.is_long {
				width: 100%;
				flex: none;
				padding-top: 30rpx;
				display: inline-flex;
				align-items: center;
				justify-content: space-between;

				.list_btn {
					min-width: 30%;
				}
			}

			.list_btn {
				margin-left: 14rpx;
				height: 36px;
				line-height: 30rpx;
				border-radius: 36rpx;
				padding: 0 20rpx;
				font-size: 24rpx;
				color: #1D1D1D;
				position: relative;
				display: inline-flex;
				align-items: center;
				justify-content: center;

				.btn_img {
					width: 40rpx;
					margin-right: 8rpx;
				}
			}

			.list_btn1 {
				background: #F2F3F8;
			}

			.list_btn2 {
				background: linear-gradient(180deg, #4BADFD 0%, #2B61EB 100%);
				color: #fff;
			}
		}
	}

	.TUI-contact-search-list-default {
		text-align: center;
	}
</style>